package com.liaogui.web.controller;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * 排行榜
 * @author liaogui
 * @date 2025/3/2 19:04
 */
@RestController
@RequestMapping("/leaderboard")
@RequiredArgsConstructor
public class LeaderboardController {
    private final RedisTemplate<String, Object> redisTemplate;

    /**
     * 初始化活动浏览数
     */
    @PostMapping("/add")
    public String add() {
        String actKey = "act:sort";
        // 活动排行榜 活动id对应浏览数
        redisTemplate.opsForZSet().add(actKey, "ACT202502281645", 20D);
        redisTemplate.opsForZSet().add(actKey, "ACT202502281650", 40D);
        redisTemplate.opsForZSet().add(actKey, "ACT202502281660", 10D);
        redisTemplate.opsForZSet().add(actKey, "ACT202502281670", 50D);
        return "初始化活动浏览数成功";
    }

    /**
     * 增加浏览次数
     */
    @PostMapping("/increment")
    public String increment() {
        String actId = "ACT202502281645";
        String viewKey = "act:sort:" + actId;
        redisTemplate.opsForZSet().incrementScore(viewKey, actId ,1);
        return "增加浏览次数成功";
    }

    /**
     * 获取浏览数排名前N名的活动
     */
    @PostMapping("/top")
    public Set<String> topAct() {
        String actKey = "act:sort";
        return redisTemplate.opsForZSet().reverseRange(actKey, 0, 3)
                .stream().map(String::valueOf).collect(Collectors.toSet());

    }
}
